package com.amox.uitest.adapter;

import static android.content.ContentValues.TAG;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.dom4j.Element;

import com.amox.uitest.kit.LogKit;
import com.amox.uitest.tcase.BaseTestCase;

import android.util.Log;

public class ScreencapAdapter extends BaseAdapter<Boolean> {
	
	public ScreencapAdapter(BaseTestCase uitest) {
		super(uitest);
	}
	
	@Override
	public Boolean adapter(Element element) throws Exception {
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String format1 = format.format(new Date());
        LogKit.error("screencap : " + format1);
        rootExecCmd("screencap -p /mnt/sdcard/util/" + format1 + ".psd");
        uitest.sleep(2000);
		
		return true;
	}
	
	private void rootExecCmd(String cmd) throws IOException {
        Process process = Runtime.getRuntime().exec("su");
        OutputStream out = process.getOutputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        try {


            out.write((cmd + "\n").getBytes("utf-8"));
            out.flush();
            out.write("exit\n".getBytes("utf-8"));
            out.flush();
            String thisLine;
            while ((thisLine = reader.readLine()) != null) {
                Log.e(TAG, " ----> " + thisLine);
            }
            while ((thisLine = error.readLine()) != null) {
                Log.e(TAG, "====> " + thisLine);
            }
            reader.close();
            out.close();
            process.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
